package com.business_clean.app.network

import android.content.Intent
import com.business_clean.app.uitl.MMKVHelper
import com.business_clean.app.uitl.ToastUtil
import com.business_clean.data.mode.baseapi.ApiResponse
import com.business_clean.ui.activity.login.LoginActivity
import com.google.gson.Gson
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.net.BaseNetConstant
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException


class TokenOutInterceptor : Interceptor {

    val gson: Gson by lazy { Gson() }

    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        return if (response.body != null && response.body!!.contentType() != null) {
            val mediaType = response.body!!.contentType()
            val string = response.body!!.string()
            val responseBody = ResponseBody.create(mediaType, string)
            val apiResponse = gson.fromJson(string, ApiResponse::class.java)
            if (apiResponse != null) {
                //判断token 失效
                if (apiResponse.code == BaseNetConstant.TOKEN_INVALID) {
                    MMKVHelper.clearAll()
                    //如果是普通的activity话 可以直接跳转，如果是navigation中的fragment，可以发送通知跳转
                    appContext.startActivity(Intent(appContext, LoginActivity::class.java).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    })
                    ToastUtil.show(apiResponse.msg);
                } else if (apiResponse.code != BaseNetConstant.SUCCESS_CODE) {
                    ToastUtil.show(apiResponse.msg);
                    return response
                }
            }
            response.newBuilder().body(responseBody).build()
        } else {
            response
        }
    }
}